package yxy.game.pm2.command.union.war;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionWarMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.war.UnionWarLogBean;
import yxy.game.pm2.module.union.war.UnionWarUnionModule;

/** 联盟战 联盟战战场日志 */
@MessageType(proto = Command.UnionWarLog, classtype = UnionWarMessage.UnionWarLogRequest.class)
public class CMD_UnionWarLog extends Command<UnionWarMessage.UnionWarLogRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionWarMessage.UnionWarLogRequest request) {
		String playerCode = messageSource.getTag();

		UnionWarMessage.UnionWarLogResponse.Builder response = UnionWarMessage.UnionWarLogResponse.newBuilder();

		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		{
			Result result = new UnionHandle().checkPlayerUnion(entry);
			if (!result.equals(Result.UnionIn)) {
				send(messageSource, response, result);
				return;
			}
		}
		UnionBean union = entry.getUnionBean();
		UnionWarUnionModule unionWarUnionModule = UnionWarUnionModule.get(union.getCode());
		if (unionWarUnionModule == null) {
			send(messageSource, response, Result.Success);
			return;
		}
		
		for (UnionWarLogBean log : unionWarUnionModule.getLogs()) {
			UnionWarMessage.UnionWarLog.Builder builder = UnionWarMessage.UnionWarLog.newBuilder();
			builder.setTime(log.getTime().getMillis());
			if (log.getPlayer().contains(playerCode)) {
				builder.setYou(true);
			}
			builder.setText(log.getText());

			response.addLogs(builder);
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, UnionWarMessage.UnionWarLogResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}